package com.dj.ms.aop;

import com.dj.ms.annotation.CollectionLengthVerify;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;

/**
 * <br>
 * <p>集合长度校验器</p>
 *
 * <br>
 * @author ZJG
 * @version 1.0
 * @date 2021/7/23 下午1:44
 */
@Slf4j
public class CollectionLengthValidator implements ConstraintValidator<CollectionLengthVerify, Collection> {

    private int lengthMax;

    @Override
    public boolean isValid(Collection collection, ConstraintValidatorContext constraintValidatorContext) {
        return CollectionUtils.isNotEmpty(collection) && collection.size() <= this.lengthMax;
    }

    @Override
    public void initialize(CollectionLengthVerify constraintAnnotation) {
        this.lengthMax = constraintAnnotation.lengthMax();
    }
}
